<?php
class BufferedCodeGenerator implements ICodeGenerator {
	
	/**
	 * The wrapped generatr
	 *
	 * @var CodeGenerator
	 */
	private $generator;
	
	private $var = null;
	private $values = array();
	
	public function __construct(CodeGenerator $generator) {
		$this->generator = $generator;
	}
	
	public function appendValueAssignment($var, $value, $type = CodeGenerator::ASSIGN_NORMAL) {
		if ($var == $this->var && $type == CodeGenerator::ASSIGN_APPEND_TEXT ) {
			$this->values[] = $value;
		} else {
			$this->flush();
			
			$this->var = $var;
			$this->values = array($value);
		}
	}
	
	public function appendCustomCode($code, $style = null) {
		$this->flush();
		$this->generator->appendCustomCode($code, $style);
	}
	
	public function appendIf($condition) {
		$this->flush();
		$this->generator->appendIf($condition);
	}
	
	public function appendEndIf() {
		$this->flush();
		$this->generator->appendEndIf();
	}
	
	public function appendElse($ifCondition = null) {
		$this->flush();
		$this->generator->appendElse($ifCondition);
	}
	
	public function appendForeach($condition) {
		$this->flush();
		$this->generator->appendForeach($condition);
	}
	
	public function appendEndForeach() {
		$this->flush();
		$this->generator->appendEndForeach();
	}
	
	public function flush() {
		if ($this->var === null)
			return;
			
		$values = array();
		$buffer = '';
		
		foreach ($this->values as $value) {
			if (gettype($value) == 'string') {
				$buffer .= $value;
			} else {
				if (strlen($buffer)) 
				{
					$values[] = self::exportString($buffer, true);
					$buffer = '';
				}
				$values[] = var_export($value, true);
			}
		}
		
		if (strlen($buffer)) {
			$values[] = self::exportString($buffer, true);
			$buffer = '';
		}
		
		if (count($values)) {
			$code = "\${$this->var} .= " . implode(' . ', $values) . ';';
			$this->generator->appendCustomCode($code);
		}
		
		$this->values = array();
	}
	
	private static function exportString($string) {
		return '"' . addcslashes($string, "\n\r\\\$\"") . '"';
	}
	
	public function output() {
		return $this->generator->output();
	}
}
?>